/**
 * cropper图片上传
 */
$(function() {
  console.log('cropper图片上传。。。');

  //触发input file
  $('#upload_btn').click(function() {
    console.log('模拟点击。。。');
    $('#btn1').trigger('click');
  });
  var $image = $('.upload-img > img');
  $image.cropper({
    aspectRatio:9 / 16,
    autoCropArea:1,
    // viewMode:0,
    dragMode:'move',
    // movable:true,
    // zoomable:true,
    // zoomOnTouch:true,
    cropBoxResizable:false,
    toggleDragModeOnDblclick:false,
    cropBoxMovable:false,
    // minContainerWidth:250,
    // minCanvasWidth:360,
    // minCanvasHeight:640,
    // preview:'.img-preview',
    crop: function(data) {
        // Output the result data for cropping image.
        // console.log($image.cropper("getCropBoxData"));
          
    },
    built: function () {
      // $avatarImg.cropper('setCropBoxData', {"left": 227, "top": 36, "width": 415, "height": 415});
      // zoomImg();
    }
  });   

  var fileName; //选择上传的文件名
  // $('#btn1').change(function(){    
  //   var file = this.files[0];
  //   fileName = file.name;
  //   console.log(fileName);
  //   var reader = new FileReader();
  //   reader.onloadstart = function(){
  //     $('.loading').show();
  //   };
  //   //reader回调，重新初始裁剪区
  //   reader.onload = function(e){
  //       // 通过 reader.result 来访问生成的 DataURL
  //       var url = reader.result;
  //       // console.log(url);
  //       //选择图片后重新初始裁剪区
  //       $image.cropper('reset', true).cropper('replace', url);
  //       $('.loading').hide();
  //       $('#sure_btn').show();
  //   };   
  //   reader.readAsDataURL(file);
  // });
  var $modal = $('#my-popup');
  $modal.siblings('.am-btn').on('click', function(e) {
      var $target = $(e.target);
      if (($target).hasClass('js-modal-open')) {
        $modal.modal();
      } else if (($target).hasClass('js-modal-close')) {
        $modal.modal('toggle');
      } else {
        $modal.modal('toggle');
      }
    });
  $modal.on('close.modal.amui',function(){
    $image.cropper('clear');
  });
  $('#btn1').change(function(){
    // $image.cropper('destroy');
    
    

    var that = this;

    lrz(that.files[0], {
        height: 1920
    })
      .then(function (rst) {
        $modal.modal('toggle');
        $image.cropper('reset', true).cropper('replace', rst.base64);
        $('.loading').hide();
        $('#sure_btn').show();
          // return rst;
      });
  });
  $('#sure_btn').click(function() {

    var $imgData = $image.cropper('getCroppedCanvas',{width:1080,height:1920});
    console.log($imgData);
    var dataurl = $imgData.toDataURL('image/png');
    var info = $image.cropper("getCropBoxData");
    cropWidth = $image.cropper("getCropBoxData").width;
    cropHeight = $image.cropper("getCropBoxData").height;
    cropTop = $image.cropper("getCropBoxData").top;
    cropLeft = $image.cropper("getCropBoxData").left;
    var img = new Image();   
    // img.src = $('.cropper-canvas > img')[0].src; 
    img.src = dataurl;
    img.onload=function(){
      $modal.modal('toggle');
      $('#upload_btn').hide();
      $('.upload-img').hide();
      $('#sure_btn').hide();
      $('.cropend-text').show();
      $('#create_btn').show();
      $('.input-group').show();
      $('#reset_crop_btn').show();
      $("html,body").scrollTop(0);
      var canvas=$('<canvas width="'+1080+'" height="'+1920+'" class="am-container" style="border:1px solid #d3d3d3" id="cropend-canvas"></canvas>')[0],
      ctx=canvas.getContext('2d');      
      ctx.drawImage(img,0,0,1080,1920,0,0,1080,1920);
      var img1 = new Image();
      var host = window.location.host;
      img1.src = 'http://'+host+'/public/static/shuiyin/images/shuiyin.png';
      img1.onload = function(){
        ctx.drawImage(img1,0,0,1080,1920,0,0,1080,1920);
      }
      $('#img-preview').append(canvas);
    }
  });
  $('#create_btn').click(function(){
    // var $imgData = $image.cropper('getCroppedCanvas',{width:360,height:640})
    // var dataurl = $imgData.toDataURL('image/png');
    var value1 = $('#value1').val();
    var value2 = $('#value2').val();
    var value3 = $('#value3').val();
    var img = new Image();
    var $canvas = $('#img-preview > canvas')[0];
    // img.src = 'http://sy/public/static/shuiyin/shuiyin.png';
    var dataurl = $canvas.toDataURL();
    // console.log(dataurl);
    img.src = dataurl ;
    img.onload=function(){
      $('.cropend-div').hide();
      $('.create-text').show();
      $("html,body").scrollTop(0);
      var canvas=$('<canvas width="'+1080+'" height="'+1920+'" class="am-container" style="display:none;" id="add-shuiyin"></canvas>')[0],
      ctx=canvas.getContext('2d');
      ctx.drawImage(img,0,0,1080,1920,0,0,1080,1920);
      ctx.font="95px Microsoft YaHei bolder";
      ctx.fillStyle = "#daaf63";
      ctx.fillText(value1,174,1611);
      ctx.font = "49px Microsoft YaHei bolder";
      ctx.fillText(value2,174,1679);
      ctx.font = "36px Microsoft YaHei bolder";
      ctx.fillText(value3,105,1725); 
      $('.create-div').append(canvas);
      var canvas = $('.create-div > canvas')[0];
      var dataurl = canvas.toDataURL("image/jpeg");
      $('.result-img').attr('src',dataurl);
      // $('#save_pic_btn').show();
      $('#reset_input_btn').show();
    }
  
  });
  $('.reset_crop_btn').click(function(){    
      $('.cropend-text').hide();
      $('#create_btn').hide();
      $('.input-group').hide();
      $('#reset_crop_btn').hide();
      $('#cropend-canvas').remove();
      $('#upload_btn').show();
      $('.upload-img').show();
      $('#sure_btn').show();
      $("html,body").scrollTop(0);
  });
  $('#reset_input_btn').click(function(){
    $("html,body").scrollTop(0);
    // $('#save_pic_btn').hide();
    $('#add-shuiyin').remove();
    $('.result-img').attr('src','');
    $('.cropend-div').show();
    $('.create-text').hide();
    $(this).hide();
    // $("#down").attr("href", "").attr("download", "");
  });
  // $('#save_pic_btn').click(function(){
  //   var canvas = $('.create-div > canvas')[0];
  //   var url = canvas.toDataURL("image/jpeg");
  //   var triggerDownload = $("#down").attr("href", url).attr("download", "result-img.jpeg");
  //   triggerDownload[0].click();
  // });
// function down() {
//     var canvas = $('.create-div > canvas')[0];
//     var url = canvas.toDataURL("image/jpeg");
//     // url = canvas.toDataURL("image/png");//PNG格式
//     //以下代码为下载此图片功能
    
// //    triggerDownload.remove();
// }

function Base64() {
 
    // private property
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
 
    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
            _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
            _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }
 
    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }
 
    // private method for UTF-8 encoding
    _utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
 
        }
        return utftext;
    }
 
    // private method for UTF-8 decoding
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}
});